package com.shanghai.shanghaielectric.UI.chart;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.shanghai.shanghaielectric.Model.ReportDateModel;
import com.shanghai.shanghaielectric.Model.EventBus.EventBusModel_Date;
import com.shanghai.shanghaielectric.R;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Alert;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_datePick;
import com.shanghai.shanghaielectric.UI.refreshView.EndLessOnScrollListener;
import com.shanghai.shanghaielectric.UI.refreshView.MyAdapter_report;
import com.shanghai.shanghaielectric.UI.refreshView.MyDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import shanghaielectric_lib.Utils.DateUtil;

/**
 * 事件-操作界面
 */
public class ChartReportFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, OnClickListener {
    public View reportView;
    @BindView(R.id.bt_clearData_report)
    Button btClearDataReport;
    @BindView(R.id.recyclerview_report)
    RecyclerView recyclerviewReport;
    @BindView(R.id.layout_swipe_refresh_report)
    SwipeRefreshLayout layoutSwipeRefreshReport;
    Unbinder unbinder;
    @BindView(R.id.bt_startTime_report)
    TextView btStartTimeReport;


    @BindView(R.id.bt_endTime_report)
    TextView btEndTimeReport;
    @BindView(R.id.bt_outpout_report)
    Button btOutpoutReport;

    private String startDate, endDate;

    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    public MyAdapter_report mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private List<ReportDateModel> reportDateModels;
    private RadioGroup tabs_warning_rg;
    private LayoutInflater myInflater;
    Button bt_clearData;
    private Context mContext;
    private int year, month, day;
    private Calendar cal;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println("EventOperation____onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getDate();
        EventBus.getDefault().register(this);
        System.out.println("EventOperation____onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("EventOperation____onCreateView");
        reportView = inflater.inflate(R.layout.chart_report_fragment, container, false);
        mContext = getActivity().getApplication().getApplicationContext();
//        myInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        unbinder = ButterKnife.bind(this, reportView);
        initData();
        initView();
//        initListener();
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        //添加分隔线
        mRecyclerView.addItemDecoration(new MyDecoration(mContext, MyDecoration.VERTICAL_LIST));
        //为RecyclerView加载Adapter
        mRecyclerView.setAdapter(mAdapter);
        //监听SwipeRefreshLayout.OnRefreshListener
        mRefreshLayout.setOnRefreshListener(this);
        /**
         * 监听addOnScrollListener这个方法，新建我们的EndLessOnScrollListener
         * 在onLoadMore方法中去完成上拉加载的操作
         * */
        mRecyclerView.addOnScrollListener(new EndLessOnScrollListener(mLinearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
//				loadMoreData();
            }
        });

        return reportView;
    }

    private void initListener() {

    }

//    LitePalHelper.OperateInfoListener operateInfoListener = new LitePalHelper.OperateInfoListener() {
//        @Override
//        public void onOperateInfoUpdate() {
//            updateData();
//        }
//    };

    public void initView() {


        btStartTimeReport.setText(startDate);
        btEndTimeReport.setText(endDate);
        bt_clearData = (Button) reportView.findViewById(R.id.bt_clearData_report);
        mRefreshLayout = (SwipeRefreshLayout) reportView.findViewById(R.id.layout_swipe_refresh_report);
        mRecyclerView = (RecyclerView) reportView.findViewById(R.id.recyclerview_report);
        mAdapter = new MyAdapter_report(mContext, reportDateModels);

        //这个是下拉刷新出现的那个圈圈要显示的颜色
        mRefreshLayout.setColorSchemeResources(
                R.color.red_color,
                R.color.yellow_color,
                R.color.green_color
        );
//        tabs_warning_rg = (RadioGroup) reportView.findViewById(R.id.tabs_warning_rg);

    }

    //初始化一开始加载的数据
    private void initData() {
        startDate = DateUtil.getSystemTime_yyyy_MM_dd_HH() + ":00";
        endDate = DateUtil.getSystemTime_yyyy_MM_dd_HH_nextDay() + ":00";

        long startTime = DateUtil.transferStringDate_yyyy_MM_dd_HH_00_long(startDate);
        long endTime = DateUtil.transferStringDate_yyyy_MM_dd_HH_00_long(endDate);

        reportDateModels = new ArrayList<>();
        DataSupport.where("date > ? and date < ?", startTime + "", endTime + "").limit(100).order("date desc").findAsync(ReportDateModel.class).listen(new FindMultiCallback() {
            @Override
            public <T> void onFinish(List<T> t) {
//                (ErrorInfoModel)t;
                reportDateModels.clear();
                reportDateModels.addAll((List<ReportDateModel>) t);
                Log.e("chartreportt", "查询到" + t.size() + "条数据");
                updateData();

//				Toast.makeText(MyApplication.getContext(),"saveAsync"+t.size(),Toast.LENGTH_LONG).show();
            }
        });//asc 正序
    }

    //每次上拉加载的时候，就加载十条数据到RecyclerView中
    private void loadMoreData() {
        DataSupport.limit(100).order("date desc").findAsync(ReportDateModel.class).listen(new FindMultiCallback() {
            @Override
            public <T> void onFinish(List<T> t) {
                reportDateModels.addAll((List<ReportDateModel>) t);
                mAdapter.notifyDataSetChanged();
            }
        });//asc 正序
    }

    /**
     * 重写SwipeRefreshLayout.OnRefreshListener的OnRefresh方法
     * 在这里面去做下拉刷新的操作
     */
    @Override
    public void onRefresh() {
//        updateData();
        //数据重新加载完成后，提示数据发生改变，并且设置现在不在刷新
    }

    private void updateData() {
//        reportDateModels.clear();
//        DataSupport.limit(100).order("date desc").findAsync(ReportDateModel.class).listen(new FindMultiCallback() {
//            @Override
//            public <T> void onFinish(List<T> t) {
//                reportDateModels.addAll(0, (List<ReportDateModel>) t);
        mAdapter.notifyDataSetChanged();
        mRefreshLayout.setRefreshing(false);


//				Toast.makeText(mContext, "正在请求数据" + t.size(), Toast.LENGTH_SHORT).show();
    }
//        });//asc 正序
//		Toast.makeText(mContext, "下拉刷新，请求数据" + reportDateModels.size(), Toast.LENGTH_SHORT).show();


//    Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//        }
//    };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("EventOperation____onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("EventOperation____onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
//        updateData();
        System.out.println("EventOperation____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("EventOperation____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("EventOperation____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("EventOperation____onDestroyView");
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        System.out.println("EventOperation____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("EventOperation____onDetach");
    }


    private void showDiolg(String commandName) {
        Dialog_Alert diolgAlert = new Dialog_Alert();
        diolgAlert.setCommandName(commandName);
        diolgAlert.show(this.getFragmentManager(), "");
    }

    private void showDiolg_datePick(String commandName) {
        Dialog_datePick dialog_datePick = new Dialog_datePick();
        dialog_datePick.setCommandName(commandName);
        dialog_datePick.show(this.getFragmentManager(), "");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_clearData_report:

                break;
        }
    }

//    @OnClick(R.id.bt_clearData_report)
//    public void onViewClicked() {
//        showDiolg("是否清空操作记录数据？");
//        Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
//            @Override
//            public void onClink(boolean flag) {
//                if (flag) {
//                    DataSupport.deleteAll(OperateInfoModel.class);
//                    Toast.makeText(mContext, "已删除...", Toast.LENGTH_SHORT).show();
//                    updateData();
//                }
//            }
//        });
//
//    }

    @Subscribe
    public void updateOperateData(ReportDateModel reportDateModel) {
        updateData();
    }

    @OnClick({R.id.bt_startTime_report, R.id.bt_endTime_report, R.id.bt_outpout_report, R.id.bt_clearData_report, R.id.bt_query_report})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_clearData_report:
                showDiolg("是否清空报表数据？");
                Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
                    @Override
                    public void onClink(boolean flag) {
                        if (flag) {
                            DataSupport.deleteAll(ReportDateModel.class);
                            Toast.makeText(mContext, "已删除...", Toast.LENGTH_SHORT).show();
                            updateData();
                        }
                    }
                });
                break;
            case R.id.bt_startTime_report:
                showDiolg_datePick("请选择起始时间");
                Dialog_datePick.setDiolgAlertListener(new Dialog_datePick.Diolg_datePickListener() {
                    @Override
                    public void onClink(String date) {
                        postEventDate(date, EventBusModel_Date.START_DATE);
                        Toast.makeText(mContext, "" + date, Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.bt_endTime_report:
                showDiolg_datePick("请选择截止时间");
                Dialog_datePick.setDiolgAlertListener(new Dialog_datePick.Diolg_datePickListener() {
                    @Override
                    public void onClink(String date) {
                        postEventDate(date, EventBusModel_Date.END_DATE);
                        Toast.makeText(mContext, "" + date, Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.bt_outpout_report:
                break;
            case R.id.bt_query_report:
                Log.e("chartreportt6", "查询数据lll");

                long startTime = DateUtil.transferStringDate_yyyy_MM_dd_HH_00_long(startDate);
                long endTime = DateUtil.transferStringDate_yyyy_MM_dd_HH_00_long(endDate);
                Log.e("chartreportt6", "查询数据" + startTime + "----" + endTime);

                DataSupport.where("date > ? and date < ?", startTime + "", endTime + "").order("date desc").findAsync(ReportDateModel.class).listen(new FindMultiCallback() {
                    @Override
                    public <T> void onFinish(List<T> t) {
//                (ErrorInfoModel)t;
                        reportDateModels.clear();
                        reportDateModels.addAll((List<ReportDateModel>) t);
                        Log.e("chartreportt6", "查询到" + t.size() + "条数据");
                        updateData();

//				Toast.makeText(MyApplication.getContext(),"saveAsync"+t.size(),Toast.LENGTH_LONG).show();
                    }
                });//asc 正序
                break;
        }
    }

    //获取当前日期
    private void getDate() {
        cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);       //获取年月日时分秒
        Log.i("wxy", "year" + year);
        month = cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day = cal.get(Calendar.DAY_OF_MONTH);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataUpdate(EventBusModel_Date eventBusModel_date) {
        if (eventBusModel_date.fragmentName.equals(ChartReportFragment.class.getName())) {
            if (EventBusModel_Date.START_DATE.equals(eventBusModel_date.dateType)) {
                startDate = eventBusModel_date.date;
                btStartTimeReport.setText(startDate);
            } else if (EventBusModel_Date.END_DATE.equals(eventBusModel_date.dateType)) {
                endDate = eventBusModel_date.date;
                btEndTimeReport.setText(endDate);

            }
        }
    }

    private void postEventDate(String date, String type) {
        EventBusModel_Date eventBusModel_date = new EventBusModel_Date();
        eventBusModel_date.fragmentName = ChartReportFragment.class.getName();

        eventBusModel_date.dateType = type;
        eventBusModel_date.date = date;
        EventBus.getDefault().post(eventBusModel_date);
    }
}
